package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishPageVo;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result insertDish(@RequestBody DishDTO dto){
        dishService.insert(dto);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result selectByCategoryId(Long categoryId){
        List<Dish> dish = dishService.selectByCategoryId(categoryId);
        return Result.success(dish);
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result selectByPage(DishPageQueryDTO queryDTO){
        DishPageVo dishVO = dishService.selectByPage(queryDTO);
        return Result.success(dishVO);
    }

    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result deleteDish(@RequestParam List ids){
        deleteCache("user_category_*");
        dishService.deleteDish(ids);
        return Result.success();
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dto){
        deleteCache("user_*");
        dishService.updateDish(dto);
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("修改启售/禁售状态")
    public Result updateStatus(@PathVariable Integer status,long id){
        deleteCache("user_*");
        dishService.updateStatus(status,id);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品")
    public Result selectById(@PathVariable Long id){
        DishVO dishVO = dishService.selectById(id);
        return Result.success(dishVO);
    }

    private void deleteCache(String patton){
        Set keys = redisTemplate.keys(patton);
        redisTemplate.delete(keys);
    }

}
